from sqlalchemy import Table, or_

from common.database import db_connect
from app.config.config import config
from model.user import User

db_session,Base,engine = db_connect()
from app.settings import env

class Article(Base):
    __table__ = Table("article", Base.metadata,autoload_with=engine)
    # 查询所有文章,不要草稿1不是0是,
    def find_article(self,page,article_type="recommend"):
    # 一页显示10条内容,page默认1开始
        if int(page) < 1:
            page = 1
        count = int(page) * config[env].page_count
        # 来到推荐分类下方
        if article_type == "recommend":
            result = db_session.query(Article,User.nickname).join(
                User,User.user_id==Article.user_id
            ).filter(
                Article.drafted == 1
            ).order_by(
                Article.browse_num.desc()).limit(count).all()
        else:
            result = db_session.query(Article,User.nickname).join(
                User, User.user_id == Article.user_id
            ).filter(
                Article.label_name == article_type,
                Article.drafted == 1
            ).order_by(
                Article.browse_num.desc()).limit(count).all()

        return result

    def search_article(self, page, keyword):
        if int(page) < 1:
            page = 1
        count = int(page) * config[env].page_count
        offset = (int(page) - 1) * config[env].page_count  # 新增偏移量
        result = db_session.query(
            Article, User.nickname
        ).join(
            User, User.user_id == Article.user_id
        ).filter(
            or_(Article.title.like("%" + keyword + "%"),
                Article.article_content.like("%" + keyword + "%"))
        ).order_by(
            Article.browse_num.desc()
        ).offset(offset).limit(count).all()  # 添加 offset
        return result


    @classmethod
    def get_detail(cls, article_id):
        """专为详情页优化的查询方法"""
        return db_session.query(
            cls,
            User.nickname,
            User.picture
        ).join(
            User, cls.user_id == User.user_id
        ).filter(
            cls.id == article_id,
            cls.drafted == 1  # 只查询已发布的文章
        ).first()

    def add_article(self, article_image, title, article_content, article_tag, article_type,
                   ):
        # 这里简单模拟生成一个图片文件名（实际应用中可能是上传处理等逻辑）

        article = Article(
            # lable_name=1,
            article_image=article_image,
            title=title,
            article_content=article_content,
            article_tag=article_tag,
            # user_id=user_id,
            # browse_num=0,
            # drafted=0,
            article_type=article_type
        )
        db_session.add(article)
        db_session.commit()
        return article
